package io.renren.modules.app.controller;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.R;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.lucky.entity.AppUserInfoEntity;
import io.renren.modules.lucky.entity.WeiXinOpenIdInfoEntiy;
import io.renren.modules.lucky.entity.WeiXinUserInfoEntiy;
import io.renren.modules.lucky.service.AppUserInfoService;
import io.renren.modules.lucky.service.AppWxUserService;
import io.renren.modules.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@Api("微信用户信息接口")
@RequestMapping("wechat")
public class AppWechatController extends AbstractController {

    //微信公众号
    private String appId = "wx0a76c766f1a7a3d8";
    private String secret = "0ebac6595fdd1cf0f61082ee8490002b";

    //微信小程序
    private String appId_xcx = "wxad67a06eab5ba883";
    private String secret_xcx = "005c5f2cfcc324c451358cf85c0955db";

    @Autowired
    private AppWxUserService wxUserService;

    @Autowired
    private AppUserInfoService appUserInfoService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * @MethodName: 微信登录授权接口
     * @Param: [map]
     * @Return: java.lang.Object
     * @Author: 泉哥倍儿帅
     * @Date: 2019/11/1
     **/
    @ApiOperation("微信登录授权接口")
    @PostMapping("/wxUsers")
    public @ResponseBody
    Object saveWxUser(@RequestBody HashMap<String, String> map) throws IOException {

        String userCode = map.get("userCode").toString();
        String latitude = map.get("latitude").toString();
        String longitude = map.get("longitude").toString();
        System.out.println(userCode);
        Map<String, Object> resultMap = new HashMap<>();

        //获取OpenId
        WeiXinOpenIdInfoEntiy openIdInfo = wxUserService.getOpenIdInfo(userCode, appId, secret, 1234);
        System.out.println(openIdInfo.toString());
        if (openIdInfo.getOpenid() == null) {
            resultMap.put("ret", "0");
            resultMap.put("code", 1);
            resultMap.put("info", "授权信息获取失败");
            logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(resultMap));
            return R.ok(resultMap);
        }

        //获取用户信息
        //code 方式自带token 毋需在获取
        WeiXinUserInfoEntiy userMess = wxUserService.getWeixinUserInfo(openIdInfo.getOpenid(), openIdInfo.getAccess_token(),latitude,longitude);
        System.out.println(userMess.toString());




        //微信是否已绑定了电话，已绑定则直接登录
        String phone = userMess.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //获取用户信息，并登录
            AppUserInfoEntity infoEntity = appUserInfoService.queryUserInfo(phone);
            resultMap.put("ret", "2");
            resultMap.put("info", "登录成功");
            resultMap.put("infoEntity", infoEntity);

            // 生成token
            String token = jwtUtils.generateToken(infoEntity.getId());
            resultMap.put("token", token);
            resultMap.put("expire", jwtUtils.getExpire());

            logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(resultMap));

            return R.ok(resultMap);

        }
        resultMap.put("ret", "1");
        resultMap.put("info", "获取授权成功");
        resultMap.put("weixinInfo", userMess);

        return R.ok(resultMap);
    }

    /**
     * @MethodName: 用户坐标接口
     * @Description: TODO
     * @Param: [map]
     * @Return: java.lang.Object
     * @Author: 泉哥倍儿帅
     * @Date: 2019/11/1
     **/
    @ApiOperation("用户坐标接口")
    @PostMapping("/wxUsersPosition")
    public @ResponseBody
    Object wxUsersPosition(@RequestBody HashMap<String, String> map) throws IOException {
        log.info("获取敌军坐标");
//        String userCode = map.get("userCode").toString();
//        System.out.println(userCode);
//        //前台获取坐标
//        String userPosition = map.get("userPosition").toString();
//        //微信获取坐标
//        WeiXinOpenIdInfoEntiy openIdInfo = wxUserService.getPosition(userCode,appId,secret,222);
//        System.out.println(openIdInfo.toString());
//        //存贮坐标
//        WeiXinUserInfoEntiy userMess = wxUserService.getUserPosition(openIdInfo.getOpenid(),openIdInfo.getAccess_token());
//
//        System.out.println(userMess.toString());
//        log.info("泉哥华丽的落幕");
//        return userMess;
        return null;
    }

    /**
     * @MethodName: 用户分享授权接口
     * @Description: TODO
     * @Param: [map]
     * @Return: java.lang.Object
     * @Author: 泉哥倍儿帅
     * @Date: 2019/11/1
     **/
    @ApiOperation("用户分享授权接口")
    @PostMapping("/wxParameter")
    public @ResponseBody
    Object wxParameter(@RequestBody HashMap<String, String> map) throws IOException {
        log.info("泉哥过来拿参数咯");
        String url = map.get("url").toString();
        Map<String, String> resultMap = new HashMap<String, String>();
        //时间戳
        String timestamp = System.currentTimeMillis() / 1000 + "";
        //随机码
        String nonceStr = UUID.randomUUID().toString();
        //获取signature
        String signature = wxUserService.getWxJsSign(url, timestamp, nonceStr);
        resultMap.put("timestamp", timestamp);
        resultMap.put("nonceStr", nonceStr);
        resultMap.put("signature", signature);
        log.info("给你给你全给你");
        return resultMap;
    }

}
